package com.zx.notification.consumer.config;

import com.zx.core.enums.StatusEnum;
import com.zx.notification.common.constants.NotificationConstants;
import com.zx.notification.common.dao.NotificationChannelsConfigMapper;
import com.zx.notification.common.model.NotificationChannelsConfig;
import com.zx.redis.block.service.RedisBlockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 统一渠道配置管理器
 * 负责管理所有MQ类型的渠道配置，提供统一的配置查询和缓存管理接口
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ChannelConfigManager {

    private final NotificationChannelsConfigMapper notificationChannelsConfigMapper;
    private final RedisBlockService redisBlockService;

    /**
     * 根据MQ类型获取启用的渠道配置（带缓存）
     *
     * @param mqType MQ类型
     * @return 渠道配置列表
     */
    public List<NotificationChannelsConfig> getActiveChannelConfigsByMqType(String mqType) {
        return notificationChannelsConfigMapper.selectByMqTypeAndStatus(mqType, StatusEnum.ENABLE.getCode());
    }

    /**
     * 根据渠道类型获取启用的渠道配置（带缓存）
     *
     * @param channelType 渠道类型
     * @return 渠道配置
     */
    public NotificationChannelsConfig getActiveChannelConfigByType(String channelType) {
        String cacheKey = NotificationConstants.RedisCache.CHANNEL_CONFIG_CACHE_KEY_PREFIX + channelType;

        try {
            // 先从Redis缓存获取
            NotificationChannelsConfig config = redisBlockService.getCachedObject(cacheKey, NotificationChannelsConfig.class);
            if (config == null) {
                // Redis缓存未命中，从数据库查询
                config = notificationChannelsConfigMapper.selectByChannelTypeAndStatus(channelType, StatusEnum.ENABLE.getCode());
                if (config != null) {
                    // 存入Redis缓存
                    redisBlockService.setCacheObject(
                            cacheKey,
                            config,
                            NotificationConstants.RedisCache.CHANNEL_CONFIG_CACHE_EXPIRE_TIME,
                            java.util.concurrent.TimeUnit.SECONDS
                    );
                }
            }

            return config;
        } catch (Exception e) {
            log.error("获取渠道配置失败，channelType: {}", channelType, e);
            // 出错时直接查询数据库，不使用缓存
            return notificationChannelsConfigMapper.selectByChannelTypeAndStatus(channelType, StatusEnum.ENABLE.getCode());
        }
    }

    /**
     * 检查渠道是否使用指定MQ类型
     *
     * @param channelType 渠道类型
     * @param mqType      MQ类型
     * @return 是否使用指定MQ类型
     */
    public boolean isChannelUsingMqType(String channelType, String mqType) {
        NotificationChannelsConfig config = getActiveChannelConfigByType(channelType);
        return config != null && mqType.equals(config.getMqType());
    }

    /**
     * 清除指定渠道类型的缓存
     *
     * @param channelType 渠道类型
     */
    public void clearChannelCache(String channelType) {
        // 清除Redis缓存
        String cacheKey = NotificationConstants.RedisCache.CHANNEL_CONFIG_CACHE_KEY_PREFIX + channelType;
        try {
            redisBlockService.deleteObject(cacheKey);
        } catch (Exception e) {
            log.warn("清除Redis缓存失败，channelType: {}", channelType, e);
        }
    }
}